<?php
include_once("./common.php");

/**
 * 刷新订单收货状态
 */

$resreshOrder = new resreshOrder($db);
$resreshOrder->start();

/**
 * 刷收货订单
 */
class resreshOrder
{
    /**
     * DB实例
     * @var dba
     */
    private $db;
    
    /**
     * 获取订单发货最小日期
     * @var unknown
     */
    private $minUnixTime = 0;
    
    /**
     * 是否开启运行日志记录
     * @var unknown
     */
    private $isOpenLog = false;
    
    private $receiveOrderArr = array();
    
    
    /**
     * 构造
     * @param dba $db
     */
    public function __construct($db)
    {
        $this->db = $db;
        $this->minUnixTime = strtotime('-4 day');
    }
    
    /**
     * 开始
     */
    public function start()
    {
        global $config;
        $startTime = time();
        $limitSize = 5;
        $limitOffset = 0;
        //获取已完成订单
        $this->getReceivedOrder($limitSize, $limitOffset);
        //更新订单已完成
        $finishOrders = $this->flagOrderFinished();
        $consumeTime = time() - $startTime;
        $output = "运行时间：{$consumeTime}秒，程序确认收货订单：{$finishOrders}";
        file_put_contents($config['webroot'].'/cache/refreshOrderReceiveStatus.log', $output);
        exit($output);
    }
    
    /**
     * 递归刷订单
     * @param unknown $limitSize
     * @param unknown $limitOffset
     */
    public function getReceivedOrder($limitSize, $limitOffset)
    {
        global $config;
        //获取未收获订单
        $orderList = $this->getWaitingOrder($limitSize, $limitOffset);
        $this->addLog('order条数'.count($orderList));
        if (empty($orderList)) {
            //处理完了
            return '';
        }
        foreach ($orderList as $v) {
            if ($this->isReceived($v['shipping_express_id'], $v['shipping_no'])) {
                $this->addLog("{$v['order_id']}已收货");
                $this->receiveOrderArr[] = array($v['order_id'], $v['member_id'],true);
            } else {
                $this->addLog("{$v['order_id']}未收货");
            }
        }
        $limitOffset += $limitSize;
        $this->getReceivedOrder($limitSize, $limitOffset);
    }
    
    /**
     * 获取未收货的订单
     */
    public function getWaitingOrder($limitSize, $limitOffset)
    {
        $splitDate = strtotime('-45 day');//分界时间，如果45天前都还没收到货，则证明快递接口有问题
        $minDate = $this->minUnixTime;
        $sql = "SELECT `order_id`,`shipping_no`,`shipping_express_id`,`member_id` FROM `haiou_order` WHERE `status`=3 AND `ship_time`>{$splitDate} AND `ship_time`<{$minDate} AND `shipping_express_id`!='1' LIMIT {$limitSize} OFFSET {$limitOffset}";
        $this->addLog($sql);
        $this->db->query($sql);
        $list = $this->db->getRows();
        return $list;
    }
    
    /**
     * 是否已收货
     */
    public function isReceived($shippingExpressId, $shippingNo)
    {
        $LogisticsExpress = $this->getLogisticsExpress();
        $subscriberCode = $LogisticsExpress[$shippingExpressId]['subscriber_code'];
        $this->addLog("获取物流:{$shippingExpressId},{$shippingNo}");
        if ($subscriberCode == '4ex') {
            //递四方快递
            $apiUrl = 'http://api.tr.4px.com/API/GetTrackingOrder.asmx/GetTrackingOrders?token=255E518B-F399-4D05-98A0-34AD94323C51&orderNo=%s';
            $apiUrl = sprintf($apiUrl,$shippingNo);
            $res = curl_file_get_contents($apiUrl);
            $res = $this->simplestXmlToArray($res);
            if (!empty($res['Data']['TrackingList']['TrackingList'])) {
                $lastContent = $res['Data']['TrackingList']['TrackingList'][0]['TrackingContent'];
                $this->addLog('递四方：'.$res['Data']['TrackingList']['TrackingList'][0]['TrackingContent']);
                if (strpos($lastContent, '已签收')) {
                    return true;
                }
            }
        } elseif ($subscriberCode != 'bee') {
            //可以走订阅路线
            $durl = 'http://app.milanoo.com/delivery/tracking/queryTrackInfo.htm?company=%s&trackingNumber=%s';
            $durl = sprintf($durl,$subscriberCode,$shippingNo);
            $res = curl_file_get_contents($durl);
            $res = @gzuncompress($res);
            if(!empty($res)){
                $resArr = json_decode($res,true);
                $this->addLog('快递100：'.$resArr['trackingInfo']['trackStatus']);
                if(!empty($resArr) && !empty($resArr['trackingInfo']) && $resArr['trackingInfo']['trackStatus'] == 'shutdown'){
                    return true;
                }
            }
        }

        return false;
    }
    
    /**
     * 获取物流公司信息
     */
    public function getLogisticsExpress() {
        static $list;
        if (empty($list)) {
            $sql = "SELECT `id`,`subscriber_code` FROM `haiou_logistics_express`";
            $this->db->query($sql);
            $res = $this->db->getRows();
            $list = array();
            if (!empty($res)) {
                foreach ($res as $v) {
                    $list[$v['id']] = $v;
                }
            }
        }
        return $list;
    }
    
    /**
     * XML转数组
     * @param unknown $xmlstring
     */
    public function simplestXmlToArray($xmlstring)
    {
        if (empty($xmlstring)) {
            return array();
        }
        return json_decode(json_encode((array) simplexml_load_string($xmlstring)), true);
    }
    
    /**
     * 记录日志
     * @param string $msg
     */
    public function addLog($msg)
    {
        global $config;
        static $fp;
        if (!$this->isOpenLog) {
            return;
        }
        $logPath = $config['webroot'].'/cache/refreshOrderReceive.run.log';
        if (!file_exists($logPath)) {
            @touch($logPath);
        }
        if (empty($fp)) {
            $fp = fopen($logPath, 'a');
        }
        $msg .= PHP_EOL;
        fwrite($fp, $msg);
    }
    
    /**
     * 标记订单为已完成
     * @param unknown $finishOrders
     */
    public function flagOrderFinished()
    {
        global $config;
        if (empty($this->receiveOrderArr)) {
            return;
        }
        $finishOrders = '';
        include_once ($config['webroot'] . "/module/product/includes/plugin_order_class.php");
        $order = new order();
        
        foreach ($this->receiveOrderArr as $v) {
            //使用后台统一的更改订单收货
//             $res = Rpc::getData('user', 'Order', 'confirmReceived', $v);//调用收货API
//             if (isset($res['code']) && $res['code'] === '0') {
//                 $finishOrders .= $v[0].','; 
//             }
            $finishOrders .= $v[0].',';
            $order->set_order_statu($v[0], 4);
        }
        return $finishOrders;
    }
}